# _*_ coding: utf-8 _*_

from fabric2 import Connection
import os
from time import sleep
from colorama import Fore
from configparser import ConfigParser


class Remote_Ceph(object):
    BASE_DIR = os.getcwd()

    def __init__(self, host=None, user=None, password=None, port=22):
        self.conn = Connection(host, user, port, connect_kwargs={'password': password})

    def make_targz(self, output_filename, source_dir):
        print(Fore.GREEN + f'正在压缩{output_filename}')
        os.system(f'tar -zcf {output_filename} {source_dir}')

    @classmethod
    def copy_file(ctl):
        print(Fore.GREEN + '正在拷贝配置')
        for i in range(2, 4):
            os.system(f"cp ceph1/etc/ceph/*  ceph{i}/etc/ceph/")
            os.system(f"cp -r ceph1/var/lib/ceph/bootstrap-*  ceph{i}/var/lib/ceph/")

    @classmethod
    def mkdir_tree(cls):
        print(Fore.GREEN + '创建需求目录')
        for i in range(1, 4):
            if not os.path.isdir(f'ceph{i}/etc/ceph'):
                os.makedirs(f'ceph{i}/etc/ceph')
            if not os.path.isdir(f'ceph{i}/mnt/cephfs'):
                os.makedirs(f'ceph{i}/mnt/cephfs')
            if not os.path.isdir(f'ceph{i}/var/lib/ceph'):
                os.makedirs(f'ceph{i}/var/lib/ceph')
            os.system(f'chmod -R 777 ceph{i}')

    @classmethod
    def master_ceph(cls):
        """
        拷贝master 配置到 slave
        :return:
        """
        cls.mkdir_tree()
        os.chdir(str(cls.BASE_DIR) + '/ceph1')
        os.system("""docker-compose up -d""")
        sleep(2)
        os.system("""docker-compose down""")
        os.system("""echo 'osd max object name len = 256' >> etc/ceph/ceph.conf""")
        os.system("""echo 'osd max object namespace len = 64' >> etc/ceph/ceph.conf""")
        os.system("""docker-compose up -d""")
        os.chdir(cls.BASE_DIR)
        cls.copy_file()

    def slave_ceph(self, home_path, zip_file):
        with self.conn.cd(home_path):
            self.conn.put(zip_file, home_path)
            self.conn.run(f'tar -zxf {zip_file}')
            with self.conn.cd(zip_file.split('.')[0]):
                self.conn.run('docker-compose up -d')


def main():
    # 读取配置文件
    basedir = os.path.abspath(os.path.dirname(__file__))
    cfg_path = os.path.join(basedir, 'config.ini')
    cfg = ConfigParser()
    cfg.read(cfg_path)

    # 启动master
    print(Fore.GREEN + '启动master'.center(100, '-'))
    Remote_Ceph.master_ceph()
    print('\n\n\n')

    # 运行slave1
    print(Fore.GREEN + '启动slave1 节点'.center(100, '-'))
    gz_name = cfg.get('ceph2', 'gz_name')
    slave1 = Remote_Ceph(host=cfg.get('ceph2', 'host'), user=cfg.get('ceph2', 'user'),
                         password=cfg.get('ceph2', 'passwd'))
    slave1.make_targz(gz_name, cfg.get('ceph2', 'local_dir'))
    slave1.slave_ceph(cfg.get('ceph2', 'remote_dir'), gz_name)
    print('\n\n\n')

    # 运行slave2
    print(Fore.GREEN + '启动slave2 节点'.center(100, '-'))
    gz_name = cfg.get('ceph3', 'gz_name')
    slave2 = Remote_Ceph(host=cfg.get('ceph3', 'host'), user=cfg.get('ceph3', 'user'),
                         password=cfg.get('ceph3', 'passwd'))
    slave2.make_targz(gz_name, cfg.get('ceph3', 'local_dir'))
    slave2.slave_ceph(cfg.get('ceph3', 'remote_dir'), gz_name)


if __name__ == '__main__':
    main()
